package com.itheima.reggie.service.iml;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedWriter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:test
 * @Create by: CAt
 * @Date;2021/9/2718:17
 */
@Service
public class DishServiceIml extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;


    //添加菜品
    @Transactional
    public  void tianjia(DishDto dishDto){
          this.save(dishDto);

        Long id = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors=flavors.stream().map((jihe)->{
            jihe.setDishId(id);
           return jihe;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }

    //菜品回显
    @Override
    public DishDto xiugai(Long id) {
        Dish byId = this.getById(id);

        DishDto dishDto=new DishDto();
       //工具类BeanUtils,方法copyProperties用于拷贝
        BeanUtils.copyProperties(byId,dishDto);

        LambdaQueryWrapper<DishFlavor> querWar=new LambdaQueryWrapper<>();
        querWar.eq(DishFlavor::getDishId,byId.getId());
        List<DishFlavor> list = dishFlavorService.list(querWar);
        dishDto.setFlavors(list);


        return dishDto;
    }


    //项目回显修改
    @Override
    public void huixianxiugai(DishDto dishDto) {
        this.updateById(dishDto);

        LambdaQueryWrapper<DishFlavor> querWar=new LambdaQueryWrapper<>();
        querWar.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(querWar);
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors=flavors.stream().map((jihe)->{
            jihe.setDishId(dishDto.getId());
            return jihe;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }
}
